﻿using BusinessEntity;
using BusinessEntity.xmglQuerryEntity;
using BusinessRule;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using Newtonsoft.Json.Linq;
using ProjectManApi.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManApi.Controllers.xmgl
{
    public class ProZhaoBiaoController : MvcControllerBase
    {
        private readonly INacosServerManager _serverManager;
        public ProZhaoBiaoController(INacosServerManager serverManager) : base(serverManager)
        {
            _serverManager = serverManager;
        }

        #region 导出
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await ProZhaoBiaoRule.GetExportList(ids, cols), "application/ms-excel", "采购招标列表.xls");
        }
        #endregion

        #region 下载模板
        [HttpGet]
        [AllowAnonymous]
        public IActionResult DownLoadTemplateTBR()
        {
            string baseDir = ConfigHelper.GetValue<string>("baseDir");
            string strpath = baseDir + "\\UpLoad\\Template\\tbr.xlsx";
            return File(FileHelper.Read(strpath), "application/ms-excel", "投标人导入模板.xlsx");
        }
        #endregion

        #region 导入
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ImportTBRMX([FromForm] IFormCollection formCollection)
        {
            try
            {
                //if (string.IsNullOrEmpty(strzbid))
                //{
                //    return Fail("招标编号strzbid不能为空");
                //}

                if (formCollection.Files.Count == 0)
                {
                    return Fail("请上传文件");
                }


                string strzbid = "";

                string baseDir = ConfigHelper.GetValue<string>("baseDir");

                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                string nfilepath = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/项目/";
                    string name = file.FileName;
                    string FileName = CommonHelper.GetUniqueId().ToString();
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;
                }

                DataTable ds = ExcelHelper.ExcelImport(nfilepath);
                List<CProTB> lists = new List<CProTB>();
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    CProTB tB = new CProTB();
                    tB.id = CommonHelper.GetUniqueId().ToString();
                    tB.zbid = strzbid;
                    //tbdw, fddbr, fddbrsfz, dbr, dbrsfz, lxdh, gslx, shxydm, zczb, clsj, tbsj, tbj
                    tB.tbdw = ds.Rows[i][0].ToString();//投标单位
                    tB.fddbr = ds.Rows[i][1].ToString();
                    tB.fddbrsfz = ds.Rows[i][2].ToString();
                    tB.dbr = ds.Rows[i][3].ToString();
                    tB.dbrsfz = ds.Rows[i][4].ToString();
                    tB.lxdh = ds.Rows[i][5].ToString();
                    tB.gslx = ds.Rows[i][6].ToString();
                    tB.shxydm = ds.Rows[i][7].ToString();
                    tB.zczb = ds.Rows[i][8].ToString().ToDecimal();
                    //9
                    if (ds.Rows[i][9].ToString().ToDate().Year == 1)
                        tB.clsj = null;
                    else
                        tB.clsj = ds.Rows[i][9].ToString().ToDate();

                    //10
                    if (ds.Rows[i][10].ToString().ToDate().Year == 1)
                        tB.tbsj = null;
                    else
                        tB.tbsj = ds.Rows[i][10].ToString().ToDate();

                    //tB.tbsj = ds.Rows[i][10].ToString().ToDate().Year == 1 ? DateTime.Now : ds.Rows[i][10].ToString().ToDate();
                    tB.tbj = ds.Rows[i][11].ToString().ToDecimal();
                    //工期
                    //tB.duration = ds.Rows[i][12].ToString();

                    lists.Add(tB);
                }

                string strcols = "";
                for (int i = 0; i < ds.Columns.Count; i++)
                {
                    strcols += ds.Columns[i].ColumnName + ",";
                }


                dynamic d = new ExpandoObject();
                d.cols = strcols.TrimEnd(',');
                d.data = ds;

                return Success(d);//lists.ToJson()
                //if (await ProZhaoBiaoRule.GetImportTBRList(lists))
                //{
                //    return Success(ds.ToJson());
                //}
                //else
                //{
                //    return Fail("导入失败");
                //}
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ImportTBRMXSubmit([FromForm] IFormCollection formCollection)
        {
            try
            {

                string strzbid = "";
                //if (string.IsNullOrEmpty(strzbid))
                //{
                //    return Fail("招标编号strzbid不能为空");
                //}

                string baseDir = ConfigHelper.GetValue<string>("baseDir");

                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                string oFileName = "";
                string nfilepath = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/项目/";
                    oFileName = file.FileName;
                    string FileName = CommonHelper.GetUniqueId().ToString();
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(oFileName);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;
                }

                DataTable ds = ExcelHelper.ExcelImport(nfilepath);
                ds.Columns.Add("错误原因");
                bool err = false;
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    string tbdw = ds.Rows[i][0].ToString();
                    if (string.IsNullOrEmpty(tbdw))
                    {
                        err = true;
                        ds.Rows[i]["错误原因"] = "投标单位不能为空";
                    }
                }

                if (!err)
                {
                    List<CProTB> lists = new List<CProTB>();
                    for (int i = 0; i < ds.Rows.Count; i++)
                    {
                        CProTB tB = new CProTB();
                        tB.id = CommonHelper.GetUniqueId().ToString();
                        tB.zbid = strzbid;
                        //tbdw, fddbr, fddbrsfz, dbr, dbrsfz, lxdh, gslx, shxydm, zczb, clsj, tbsj, tbj
                        tB.tbdw = ds.Rows[i][0].ToString();//投标单位
                        tB.fddbr = ds.Rows[i][1].ToString();
                        tB.fddbrsfz = ds.Rows[i][2].ToString();
                        tB.dbr = ds.Rows[i][3].ToString();
                        tB.dbrsfz = ds.Rows[i][4].ToString();
                        tB.lxdh = ds.Rows[i][5].ToString();
                        tB.gslx = ds.Rows[i][6].ToString();
                        tB.shxydm = ds.Rows[i][7].ToString();
                        tB.zczb = ds.Rows[i][8].ToString().ToDecimal();
                        //tB.clsj = ds.Rows[i][9].ToString().ToDate().Year == 1 ? null : ds.Rows[i][9].ToString().ToDate();
                        //tB.tbsj = ds.Rows[i][10].ToString().ToDate().Year == 1 ? null : ds.Rows[i][10].ToString().ToDate();
                        if (ds.Rows[i][9].ToString().ToDate().Year == 1)
                            tB.clsj = null;
                        else
                            tB.clsj = ds.Rows[i][9].ToString().ToDate();

                        //10
                        if (ds.Rows[i][10].ToString().ToDate().Year == 1)
                            tB.tbsj = null;
                        else
                            tB.tbsj = ds.Rows[i][10].ToString().ToDate();

                        tB.tbj = ds.Rows[i][11].ToString().ToDecimal();

                        lists.Add(tB);
                    }


                    return Success(lists.ToJson());

                    //if (await ProZhaoBiaoRule.GetImportTBRList(lists))
                    //{
                    //    return Success(lists.ToJson());
                    //}
                    //else
                    //{
                    //    return Fail("导入失败");
                    //}
                }
                else
                {
                    //设置导出格式
                    ExcelConfig excelconfig = new ExcelConfig();
                    excelconfig.Title = "投标人";// 文件名称;
                    excelconfig.TitleFont = "微软雅黑";
                    excelconfig.TitlePoint = 25;
                    //excelconfig.HeadPoint = 12;
                    excelconfig.FileName = oFileName;
                    excelconfig.IsAllSizeColumn = true;
                    //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
                    excelconfig.ColumnEntity = new List<ColumnModel>();
                    for (int i = 0; i < ds.Columns.Count; i++)
                    {
                        excelconfig.ColumnEntity.Add(new ColumnModel() { Column = ds.Columns[i].ColumnName, ExcelColumn = ds.Columns[i].ColumnName });
                    }

                    Response.StatusCode = 201;
                    return File(ExcelHelper.ExportMemoryStream(ds, excelconfig), "application/ms-excel", oFileName.LastIndexOf('.') + ".xls");
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 202;
                return Fail(ex.Message);
            }
        }
        #endregion

        #region 投标人明细 新增 修改 删除

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tbr"></param>
        /// <param name="strope"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> OPECProTBRMX(CProTB tbr, string strope)
        {
            try
            {
                strope = strope.ToLower();
                if (strope != "add" && strope != "edit" && strope != "del")
                {
                    //只能是[add,edit]
                    return Fail("ope参数类型错误");
                }

                string Cuid = GetUserId();
                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(tbr.zbid))
                    {
                        return Fail("修改操作，zbid不能为空");
                    }

                    tbr.id = CommonHelper.GetUniqueId().ToString();
                    tbr.createuser = Cuid;
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(tbr.id))
                    {
                        return Fail("修改操作，明细id不能为空");
                    }
                }
                else if (strope == "del")
                {
                    if (string.IsNullOrEmpty(tbr.id))
                    {
                        return Fail("修改操作，明细id不能为空");
                    }
                }

                await BusinessRule.ProZhaoBiaoRule.InsertTBXXMX(tbr, strope);

                return Success("成功");
            }
            catch (Exception ex)
            {
                //return Fail("响应失败");
                return Fail(ex.Message);
            }
        }
        #endregion

        #region ProZhaoBiaoLists列表，获取单条-标段信息、项目信息，新增修改ProZhaoBiaoAdd.aspx、删除


        /// <summary>
        /// 项目招标列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="xmfl"></param>
        /// <param name="jsdw"></param>
        /// <param name="status"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetZBIndexList(string formCode, string cgmc, string xmmc, string dxmc, string cgfs, string xmfl, string jsdw, string zbstatus, string status, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "")
        {
            try
            {
                ProZhaoBiaoQuerry querry = new ProZhaoBiaoQuerry();
                //调用审批
                querry.formCode = formCode;

                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.cgmc = cgmc;
                querry.dxmc = dxmc;
                querry.cgfs = cgfs;

                querry.Jsdw = jsdw;
                querry.Xmmc = xmmc;
                querry.Xmfl = xmfl;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;
                //招标状态
                querry.zbzt = zbstatus;
                querry.has = "all";

                (IEnumerable<dynamic>, int) SelectTable = await ProZhaoBiaoRule.GetZBIndexList(querry, await GetDepId());//GetUserId()


                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.zbid;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.zbid;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);

                    //if (null != spstatus)
                    //{
                    //    dynamic panguData = new ExpandoObject();
                    //    panguData.taskId = spstatus.taskId;
                    //    panguData.instanceId = spstatus.processInstanceId;
                    //    panguData.reviewStatus = item.spstatus;
                    //    panguData.approvalAuth = spstatus.approvalAuth;
                    //    panguData.cancelAuth = spstatus.cancelAuth;
                    //    panguData.restartAuth = spstatus.restartAuth;
                    //    item.panguData = panguData;
                    //}
                    //else
                    //{
                    //    dynamic panguData = new ExpandoObject();
                    //    panguData.reviewStatus = item.spstatus;
                    //    item.panguData = panguData;
                    //}
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //弹窗
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetZBIndexListC(string formCode, string cgmc, string xmmc, string dxmc, string cgfs, string xmfl, string jsdw, string zbstatus, string status, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "")
        {
            try
            {
                ProZhaoBiaoQuerry querry = new ProZhaoBiaoQuerry();
                //调用审批
                querry.formCode = formCode;

                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.cgmc = cgmc;
                querry.dxmc = dxmc;
                querry.cgfs = cgfs;

                querry.Jsdw = jsdw;
                querry.Xmmc = xmmc;
                querry.Xmfl = xmfl;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;
                //招标状态
                querry.zbzt = zbstatus;
                querry.has = "1";

                (IEnumerable<dynamic>, int) SelectTable = await ProZhaoBiaoRule.GetZBIndexList(querry, await GetDepId());//GetUserId()


                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.zbid;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.zbid;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);

                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据标段id获取单条标段招标信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZBByBDId(string keyValue)
        {
            try
            {
                var SelectTable = await ProZhaoBiaoRule.GetZBByBDId(keyValue);

                if (null != SelectTable)
                {
                    string zbid = SelectTable.zbid;
                    SelectTable.tbxx = await ProZhaoBiaoRule.GetTBXXByBDId(zbid);

                    //添加了采购信息
                    SelectTable.cgxx = await ProCaiGouRule.GetXMCGEntityByDxid(keyValue);
                }

                //List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formcode, GetUserName(), new List<string>() { zbid }, await GetICApiInfo());
                //var spstatus = spitems.Where(ii => ii.businessId == zbid).FirstOrDefault();
                //SelectTable.panguData = GetPanGudData(spstatus, SelectTable.spstatus);


                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入不需要招标信息
        /// </summary>
        /// <param name="zbjson"></param>
        /// <param name="strope"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> InsertCProZBNOTender(dynamic zbjson)//, string strope = "xxx"
        {

            string strope = "add";
            CProZB cprozb = new CProZB();
            List<CProTB> tbs = new List<CProTB>();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)zbjson;

                //获取方法
                strope = zbjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                cprozb = job["zbxx"].ToObject<CProZB>();

                if (null != job["tbxx"])
                    tbs = job["tbxx"].ToObject<List<CProTB>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (string.IsNullOrEmpty(strope) || (strope != "add" && strope != "edit" && strope != "submit"))
                {
                    return Fail("ope参数错误");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                
                if (strope == "add")
                {

                    if (string.IsNullOrEmpty(cprozb.dxid))
                    {
                        return Fail("标段编号不能为空");
                    }
                    //if (string.IsNullOrEmpty(cprozb.zbfs))
                    //{
                    //    return Fail("采购方式不能为空");
                    //}
                    //if (cprozb.zbje.ToDecimal() == 0)
                    //{
                    //    return Fail("成交金额不能为空");
                    //}
                    //if (string.IsNullOrEmpty(cprozb.zbdw))
                    //{
                    //    return Fail("成交单位不能为空");
                    //}

                    cprozb.id = CommonHelper.GetUniqueId().ToString();

                    //prozb.id = CommonHelper.GetUniqueId().ToString();
                    cprozb.createuser = GetUserId();
                    cprozb.status = BaseEditPower.GetSPEnumValue("通过");//直接过？
                    cprozb.lx = "bzb";//不招标

                    //if (strlsope != "submit")
                    //    cprozb.status = BaseEditPower.GetSPEnumValue("待提交");

                    ////这里先绑定附件
                    //await JavaApi.UploadFileJavaAPI(cprozb.id, filecodes, await GetICApiInfo());

                    //bool bsp = true;
                    //if (strlsope == "submit")
                    //{
                    //    bsp = false;
                    //    JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.招标.ToString(), cprozb.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(zbjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus");
                    //    bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                    //    if (!bsp)
                    //    {
                    //        return Fail("提交失败，启动工作流异常");
                    //    }
                    //}

                    await BusinessRule.ProZhaoBiaoRule.InsertCProZBNOTender(cprozb, GetUserId(), strope);

                    return Success("成功");
                }
                //修改要判断权限
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(cprozb.id))
                    {
                        return Fail("招标id不能为空");
                    }

                    cprozb.createuser = GetUserId();
                    cprozb.status = BaseEditPower.GetSPEnumValue("通过");//直接过？
                    cprozb.lx = "bzb";//不招标

                    CProZB jhe = await TranstionRule.FindEntityByKey<CProZB>(cprozb.id);
                    //之前是招标的  就得判断状态
                    if (jhe.lx != "bzb")
                    {
                        if (CommonHelper.ParseInt(jhe.status) >= 0)
                        {
                            return Fail("响应失败:请确认数据权限");
                        }
                    }

                    await BusinessRule.ProZhaoBiaoRule.InsertCProZBNOTender(cprozb, GetUserId(), strope);
                }

                //不需要招标
                //zb.status = "4";
                //await BusinessRule.ProZhaoBiaoRule.InsertCProZBNOTender(zb, GetUserId(), strope);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入不需要招标信息
        /// </summary>
        /// <param name="zbjson"></param>
        /// <param name="strope"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> InsertCProZBNOTenderN(dynamic zbjson)//, string strope = "xxx"
        {

            string strope = "add";

            List<string> dxs = new List<string>();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)zbjson;

                //获取方法
                strope = zbjson.ope ?? "";
                strope = strope.ToLower();


                if (null != job["dxs"])
                    dxs = job["dxs"].ToObject<List<string>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (string.IsNullOrEmpty(strope) || (strope != "n" && strope != "y"))
                {
                    return Fail("ope参数错误");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                if (strope == "n")
                {
                    for (int i = 0; i < dxs.Count; i++)
                    {
                        string strdxid = dxs[i];
                        if (!string.IsNullOrEmpty(strdxid))
                        {
                            CProZB jhe = await TranstionRule.FindEntity<CProZB>(new { dxid = strdxid });
                            if (null == jhe)
                            {

                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(jhe.lx) && jhe.lx == "zb")
                                {
                                    return Fail("所选数据中有部分数据已提交了招标申请");
                                }
                            }
                        }
                        else
                        {
                            return Fail("标段编号不能为空");
                        }
                    }
                }

                else if (strope == "y")
                {
                    for (int i = 0; i < dxs.Count; i++)
                    {
                        string strdxid = dxs[i];
                        if (!string.IsNullOrEmpty(strdxid))
                        {
                            CProZB jhe = await TranstionRule.FindEntity<CProZB>(new { dxid = strdxid });
                            if (null == jhe)
                            {

                            }
                            else
                            {
                                if (!(jhe.lx == "bzb"))
                                {
                                    return Fail("所选数据中有部分数据已提交了招标申请");
                                }
                            }
                        }
                        else
                        {
                            return Fail("标段编号不能为空");
                        }
                    }
                }


                List<CProZB> lists = new List<CProZB>();
                for (int i = 0; i < dxs.Count; i++)
                {
                    CProZB zb = new CProZB();
                    zb.id = CommonHelper.GetUniqueId().ToString();

                    zb.lx = "bzb";

                    zb.dxid = dxs[i];
                    zb.status = "2";
                    zb.createdate = DateTime.Now;
                    zb.createuser = GetUserId();

                    lists.Add(zb);
                }

                await BusinessRule.ProZhaoBiaoRule.InsertCProZBNOTender(lists, GetUserId(), strope);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProZB(dynamic zbjson)
        {
            string strope = "add";
            CProZB cprozb = new CProZB();
            List<CProTB> tbs = new List<CProTB>();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)zbjson;

                //获取方法
                strope = zbjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                cprozb = job["zbxx"].ToObject<CProZB>();

                if (null != job["tbxx"])
                    tbs = job["tbxx"].ToObject<List<CProTB>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (string.IsNullOrEmpty(strope) || (strope != "add" && strope != "edit" && strope != "zb" && strope != "submit"))
                {
                    return Fail("ope参数错误");
                }


            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }


            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(cprozb.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProZB jhe = await TranstionRule.FindEntityByKey<CProZB>(cprozb.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    cprozb.status = BaseEditPower.GetSPEnumValue("待审核");

                    if (string.IsNullOrEmpty(cprozb.zbfs))
                    {
                        return Fail("招标方式不能为空");
                    }
                }


                //常州
                //cprozb.zbzt = "2";//中标状态

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(cprozb.dxid))
                    {
                        return Fail("标段编号不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbxmcglb))
                    {
                        return Fail("采购类别不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbxmcgfs))
                    {
                        return Fail("采购方式不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbxmcgysje))
                    {
                        return Fail("采购预算金额不能为空");
                    }

                    string strdepid = GetUserDeptid();

                    //bool runs = await FunSetRule.GetFunSet(strdepid,BaseEditPower.JumpModule.采购计划.ToString());
                    var runs = await CProTZJHRule.GetFunGLListBylxEunm(BaseEditPower.JumpModule.采购计划.ToString());

                    if (runs == "1")
                    {
                        CProZBLS cg = await TranstionRule.FindEntity<CProZBLS>(new { dxid = cprozb.dxid, status = "2" });
                        if (null == cg)
                        {
                            return Fail("请先完成采购申请，再填报招标申请");
                        }
                    }


                    cprozb.id = CommonHelper.GetUniqueId().ToString();
                    cprozb.dxnm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.招标.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(zbjson), await GetICApiInfo());
                    //await BusinessRule.Assets.CreateZCDM("XM", "ZB");

                    if (strlsope != "submit")
                        cprozb.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(cprozb.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.招标.ToString(), cprozb.dxid);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = cprozb.dxnm, amount = cprozb.bdje?.ToString(), content = "[项目招标]" + cprozb.remark, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.招标.ToString(), cprozb.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(cprozb), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        cprozb.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProZhaoBiaoRule.InsertCProZB(cprozb, tbs, GetUserId(), strope);

                    return Success("成功");
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(cprozb.id))
                    {
                        return Fail("招标编号id不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.dxid))
                    {
                        return Fail("标段编号dxid不能为空");
                    }
                    //if (string.IsNullOrEmpty(cprozb.zbfs))
                    //{
                    //    return Fail("招标方式zbfs不能为空");
                    //}

                    if (string.IsNullOrEmpty(cprozb.zbxmcglb))
                    {
                        return Fail("采购类别不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbxmcgfs))
                    {
                        return Fail("采购方式不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbxmcgysje))
                    {
                        return Fail("采购预算金额不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(cprozb.id, BaseEditPower.TableName.招标))
                    {
                        return Fail("响应失败:请确认数据权限");
                    }



                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(cprozb.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        CProZB jhe = await TranstionRule.FindEntityByKey<CProZB>(cprozb.id);
                        if (null == jhe)
                        {
                            return Fail("根据id未检索到招标信息");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.招标.ToString(), cprozb.dxid);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.dxnm, amount = cprozb.bdje?.ToString(), content = "[项目招标]" + cprozb.remark, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.招标.ToString(), cprozb.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(cprozb), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        cprozb.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProZhaoBiaoRule.InsertCProZB(cprozb, tbs, GetUserId(), strope);

                    return Success("成功");
                }
                else if (strope == "zb")
                {
                    if (string.IsNullOrEmpty(cprozb.id))
                    {
                        return Fail("招标编号id不能为空");
                    }
                    if (cprozb.zbje == 0)
                    {
                        return Fail("中标金额zbje不能为空");
                    }
                    if (string.IsNullOrEmpty(cprozb.zbdw))
                    {
                        return Fail("中标单位zbdw不能为空");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(cprozb.id, filecodes, await GetICApiInfo());

                    await BusinessRule.ProZhaoBiaoRule.InsertCProZB(cprozb, tbs, GetUserId(), strope);

                    return Success("成功");
                }

                else
                {
                    return Fail("ope：" + strope + " ,无法识别");
                }
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        ///// <summary>
        ///// 插入修改（不用了）
        ///// </summary>
        ///// <param name="zb"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> InsertCProZBBY(CProTB zb)
        //{
        //    try
        //    {

        //        //if (string.IsNullOrEmpty(zb.dxid))
        //        //{
        //        //    return Fail("标段编号不能为空");
        //        //}

        //        //await BusinessRule.ProZhaoBiaoRule.InsertCProZB(zb,null, GetUserId(),"edit");

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}

        /// <summary>
        /// 根据标段id删除多条数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProZBMulti(Root ids)
        {
            try
            {
                //判断权限
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    CProZB ezb = await TranstionRule.FindEntityByKey<CProZB>(idm.id);
                    if (null != ezb)
                    {
                        if (!await BaseEditPower.GetEditPowerZB(ezb.id, BaseEditPower.TableName.招标))
                        {
                            throw new Exception("请确认数据权限");
                        }
                    }
                }

                await BusinessRule.ProZhaoBiaoRule.DeleteCProZBMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        #endregion


        #region 招标代理机构

        [HttpGet]
        //string formCode, string xmmc, string dxmc, string zbdljg, string sqdw, string datebeg, string dateend, string zbdlzt, string status, string current = "1", string size = "20", string sort = "desc", string column = ""
        public async Task<IActionResult> GetZBDLJGList([FromQuery] ProZBDLJGQuerry querry)
        {
            try
            {
                //ProZBDLJGQuerry querry = new ProZBDLJGQuerry();
                ////基础属性
                //querry.size = CommonHelper.ParseInt(size);
                //querry.current = CommonHelper.ParseInt(current);
                //querry.sort = sort;
                //querry.column = column;


                //querry.xmmc = xmmc;
                //querry.dxmc = dxmc;
                //querry.status = status;

                //querry.zbdlzt = zbdlzt;

                //querry.dljgmc = zbdljg;
                //querry.sqdw = sqdw;
                //querry.datebeg = datebeg;
                //querry.dateend = dateend;

                querry.zbdlzt = "1";

                (IEnumerable<dynamic>, int) SelectTable = await ProZhaoBiaoRule.GetZBDLJGList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(querry.formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //弹窗
        [HttpGet]
        //[AllowAnonymous]
        //string xmmc, string dxmc, string current = "1", string size = "20", string sort = "desc", string column = ""
        public async Task<IActionResult> GetNNZBDLJGList([FromQuery] ProZBDLJGQuerry querry)
        {
            try
            {
                //ProZBDLJGQuerry querry = new ProZBDLJGQuerry();
                ////基础属性
                //querry.size = CommonHelper.ParseInt(size);
                //querry.current = CommonHelper.ParseInt(current);
                //querry.sort = sort;
                //querry.column = column;


                //querry.xmmc = xmmc;
                //querry.dxmc = dxmc;
                 

                //
                querry.zbdlzt = "0";


                (IEnumerable<dynamic>, int) SelectTable = await ProZhaoBiaoRule.GetZBDLJGList(querry, await GetDepId());//GetUserId()


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据标段id获取代理机构信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZBDLJGBydxid(string dxid)
        {
            try
            {
                var SelectTable = await ProZhaoBiaoRule.GetZBDLJGBydxid(dxid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据机构id获取代理机构信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZBDLJGByid(string id)
        {
            try
            {
                var SelectTable = await ProZhaoBiaoRule.GetZBDLJGByid(id);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 根据根据htid删除多条结算数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteZBDLJGMulti(Root ids)
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.招标代理机构))
                    {
                        throw new Exception("请确认数据权限");
                    }
                }

                await BusinessRule.ProZhaoBiaoRule.DeleteZBDLJGMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入修改缺陷期数据
        /// </summary>
        /// <param name="js"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertZBDLJG(dynamic zbdljson)
        {
            string strope = "add";
            CProZBdljg zbdljg = new CProZBdljg();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)zbdljson;

                //获取方法
                strope = zbdljson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                zbdljg = job["zbdl"].ToObject<CProZBdljg>();


                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "submit")//&& strope != "edit" && strope != "approved"
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(zbdljg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProZBdljg jhe = await TranstionRule.FindEntityByKey<CProZBdljg>(zbdljg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    zbdljg.status = BaseEditPower.GetSPEnumValue("待审核");
                }


                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(zbdljg.dxid))
                    {
                        return Fail("招标代理机构信息dxid不能为空");
                    }

                    zbdljg.id = CommonHelper.GetUniqueId().ToString();
                    zbdljg.bm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.招标代理机构.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(zbdljson), await GetICApiInfo());
                    zbdljg.sqrq = DateTime.Now;


                    if (strlsope != "submit")
                        zbdljg.status = BaseEditPower.GetSPEnumValue("待提交");

                    zbdljg.createuser = GetUserId();
                    zbdljg.createdate = DateTime.Now;

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(zbdljg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;


                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.招标代理机构.ToString(), zbdljg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = zbdljg.id, amount = "0", content = "[招标代理机构]", deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.招标代理机构.ToString(), zbdljg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(zbdljson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                        zbdljg.spl = strInstanceId;
                    }

                    await ProZhaoBiaoRule.InsertZBDLJG(zbdljg, strope);
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(zbdljg.id))
                    {
                        return Fail("招标代理机构信息id不能为空");
                    }
                    if (string.IsNullOrEmpty(zbdljg.dxid))
                    {
                        return Fail("招标代理机构信息dxid不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(zbdljg.id, BaseEditPower.TableName.招标代理机构))
                    {
                        throw new Exception("请确认数据权限");
                    }


                    zbdljg.createuser = GetUserId();
                    zbdljg.createdate = DateTime.Now;

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(zbdljg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.招标代理机构.ToString(), zbdljg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = zbdljg.id, amount = "0", content = "[招标代理机构]", deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.招标代理机构.ToString(), zbdljg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(zbdljson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                        zbdljg.spl = strInstanceId;
                    }

                    await ProZhaoBiaoRule.InsertZBDLJG(zbdljg, strope);
                }

                return Success("操作成功");

            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        #endregion
    }
}
